<template>
  <h1>App根组件</h1>
  <my-table :data="goodslist">
    <template #header>
      <th>#</th>
      <th>商品名称</th>
      <th>价格</th>
      <th>标签</th>
      <th>操作</th>
    </template>
    <template #body={row,index}>
      <th>{{ index + 1 }}</th>
      <th>{{ row.goods_name }}</th>
      <th>&yen; {{ row.goods_price }}</th>
      <th>
        <input type="text" class="form-control form-control-sm form-ipt" v-if="row.inputVisible" v-focus v-model.trim="row.inputValue" @blur="oninputconfirm(row)" @keyup.enter="oninputconfirm(row)" @keyup.esc="clearinputvalue(row)">
        <button type="button" class="btn btn-primary btn-sm" v-else @click="row.inputVisible = !row.inputVisible ">+tags</button>
        <span class="badge badge-warning ml-2" v-for="item in row.tags" :key="item">{{ item }}</span>
      </th>
      <th>
        <button type="button" class="btn btn-danger btn-sm" @click="onremove(row.id)">删除</button>
      </th>
    </template>
  </my-table>
</template>

<script>
import MyTable from './components/MyTable/MyTable.vue'
export default {
  name: 'MyApp',
  components: {
    MyTable
  },
  data() {
    return {
      goodslist: []
    }
  },
  created() {
    this.getgoodslist()
  },
  directives: {
    focus(el) {
        el.focus()
    }
  },
  methods: {
    async getgoodslist() {
    const { data: res } =  await this.$http.get('/api/goods')
    console.log(res)
    if(res.status !== 0 ) return console.log('获取数据列表失败！')
    this.goodslist = res.data
    },
    onremove(id) {
      console.log(id)
    this.goodslist = this.goodslist.filter(x=>x.id !== id)
    },
    oninputconfirm(row) {
      const val = row.inputValue
      row.inputValue = ''
      row.inputVisible = false
      if(!val || row.tags.indexOf(val) !== -1) return
      row.tags.push(val)
    },
    clearinputvalue(row) {
      row.inputValue = ''
    }
  }
}
</script>

<style lang="less" scoped>
  .form-ipt {
    width: 80px;
    display: inline;
  }
</style>
